# -*- coding: utf-8 -*-
import sys
import os
sys.path.append('..')
from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
get_wsgi_application()
from backend.models import *
from django.db.models import Q
import time
from django.db import connections

"""每月1日00:01:00执行该脚本，将所有待结算分成订单按分销商汇总统计
    备注：该脚本使用crontab形式启动
    1. 查询 distributors_orders表中所有待支付且没有关联结算ID的分成订单
    2. 生产结算订单号
    3. 更新分成订单表的settlement_id, 在distributors_settlement生产一条新的记录
"""

def get_order_code():
    return str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())))+ str(time.time()).replace('.', '')[-7:]


def main():
    tmp_dict = {}
    with connections['default'].cursor() as cursor:
        cursor.execute('select id, commission, state, distributor_id from distributors_orders where state=1 and settlement_id is NULL')
        rslt = cursor.fetchall()
        for x in rslt:
            distributor_dict = tmp_dict.setdefault(x[3], {})
            distributor_dict.setdefault('ids', []).append(x[0])
            distributor_dict['total_commission'] = (distributor_dict['total_commission'] + x[1]) if 'total_commission' in distributor_dict else x[1]
        for key in tmp_dict:
            tmp_order_code = get_order_code()
            DistributorSettlement.objects.create(settlement_id=tmp_order_code, amount=tmp_dict[key]['total_commission'], state=1, distributor_id=key)
            DistributorOrder.objects.filter(id__in=tmp_dict[key]['ids']).update(settlement_id=tmp_order_code)



if __name__ == '__main__':
    main()